<?php

namespace Biz\model\package;

use Doraemon\pockets\datebase\BaseDbModel;
use Medoo\Medoo;

class PackageLogistics extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db';
    const _CONFIG_SELECT_ = 'db_activity';
    const _DATABASE_ = 'hhz_activity';
    const _TABLE_NAME = 'new_user_package_order_logistics';

    //  2、已发货, 3、已签收, 4、物流异常

    const STATUS_NORMAL = 1;
    const STATUS_DELETE = 9;
    const STATUS_EXPRESS = 2;
    const STATUS_RECEIVED = 3;
    const STATUS_LOGISTICS_FAIL = 4;

    const STATUS_MAP = [
        self::STATUS_NORMAL => '待发货',
        self::STATUS_EXPRESS => '已发货',
        self::STATUS_RECEIVED => '已签收',
        self::STATUS_LOGISTICS_FAIL => '物流异常',
    ];

    public static function selectByWhere($where, $select = '*')
    {
        $list = self::select($select, $where);
        return $list;
    }

    public static function getByWhere($where)
    {
        return self::get('*', $where);
    }

    public static function selectCount($where)
    {
        return self::count($where);
    }

    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = time();
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = time();
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return self::id();
    }

    public static function insertOrUpdate($data)
    {
        $where = ['goods_id' => $data['goods_id'], 'order_no'=>$data['order_no']];
        $res = self::getByWhere($where);
        if (!empty($res)) {
            return self::update($data, ['id' => $res['id']]);
        } else {
            return self::insertData($data);
        }
    }

    public static function updateData($data, $where)
    {
        $data['edittime'] = time();
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function getLogisticsCount(array $orders)
    {
        $result = [];
        $where = [
            'order_no' => $orders,
            'GROUP' => ['order_no']
        ];
        $res = self::select(['count' => Medoo::raw("count(id)"), 'order_no'], $where);
        $list = array_column($res, null, 'order_no');
        foreach ($orders as $order) {
            if (isset($list[$order])) {
                $result[$order] = $list[$order]['count'];
            } else {
                $result[$order] = 0;
            }
        }
        return $result;
    }

}

